package com.rth.vedio.infra.basic.config.interceptor;


import com.rth.common.context.LoginContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;


@Component
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {
        MappedStatement.class, Object.class
})})

public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (Objects.isNull(parameter)) {
            invocation.proceed();
        }
        //获取当前登录用户的id
        String loginId = LoginContextHolder.getLoginId();
        if (StringUtils.isBlank(loginId)) {
            invocation.proceed();
        }
        if (sqlCommandType.equals(SqlCommandType.INSERT) || sqlCommandType.equals(SqlCommandType.UPDATE)) {
            replaceEntityProperty(parameter, loginId, sqlCommandType);
        }

        return invocation.proceed();
    }

    private void replaceEntityProperty(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        replace(parameter, loginId, sqlCommandType);
    }

    private void replace(Object parameter, String loginId, SqlCommandType sqlCommandType) {

        if (sqlCommandType.equals(SqlCommandType.INSERT)) {
            dealInsert(parameter, loginId);
        } else if (sqlCommandType.equals(SqlCommandType.UPDATE)) {
            dealUpdate(parameter, loginId);
        }
    }

    @SneakyThrows
    private void dealUpdate(Object parameter, String loginId) {
        List<Field> fieldList = new LinkedList<>();
        Class<?> clazz = parameter.getClass();
        while (Objects.nonNull(clazz)) {
            fieldList.addAll(Arrays.asList(parameter.getClass().getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        for (Field field : fieldList) {
            field.setAccessible(true);
            if (field.getName().equals("updatedBy")) {

                field.set(parameter, loginId);
            } else if (field.getName().equals("updatedTime")) {
                field.set(parameter, new Date());
            }
            field.setAccessible(false);
        }
    }

    @SneakyThrows
    private void dealInsert(Object parameter, String loginId) {
        List<Field> fieldList = new LinkedList<>();
        Class<?> clazz = parameter.getClass();
        while (Objects.nonNull(clazz)) {
            fieldList.addAll(Arrays.asList(parameter.getClass().getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        for (Field field : fieldList) {
            field.setAccessible(true);
            if (field.getName().equals("createdBy")) {
                field.set(parameter, loginId);
            } else if (field.getName().equals("createdTime")) {
                field.set(parameter, new Date());
            } else if (field.getName().equals("isDeleted")) {
                field.set(parameter, 0);
            }
            field.setAccessible(false);
        }

    }

    @Override
    public Object plugin(Object target) {

        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
